import { deleteNotice, getMessage, readMessage } from "@/api/system";
import type { PaginationProps } from "@pureadmin/table";
import type { FormItemProps } from "element-plus";
export function useNotice(tableRef: Ref, val = "1") {
  const activeName = ref(val);
  const form = reactive({
    read: null,
    title: ""
  });
  const loading = ref(false);
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });
  const resetForm = formEl => {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  };
  function handleSizeChange(val: number) {
    pagination.pageSize = val;
    onSearch();
  }

  function handleCurrentChange(val: number) {
    pagination.currentPage = val;
    onSearch();
  }
  const selectedNum = ref(0);
  /** 当CheckBox选择项发生变化时会触发该事件 */
  function handleSelectionChange(val: FormItemProps[]) {
    selectedNum.value = val.length;
    // 重置表格高度
    tableRef.value.setAdaptive();
  }

  /** 取消选择 */
  function onSelectionCancel() {
    selectedNum.value = 0;
    // 用于多选表格，清空用户的选择
    tableRef.value.getTableRef().clearSelection();
  }

  /** 删除 */
  async function onDel(id) {
    await deleteNotice({ id });
    onSearch();
  }
  const dataList = ref([]);
  function onSearch() {
    loading.value = true;
    getMessage(activeName.value, {
      ...form,
      pageSize: pagination.pageSize,
      currentPage: pagination.currentPage
    })
      .then(data => {
        dataList.value = data.list;
        pagination.total = data.total;
        pagination.pageSize = data.pageSize;
        pagination.currentPage = data.currentPage;
      })
      .finally(() => {
        loading.value = false;
      });
  }
  // 已读消息
  async function onRead(id) {
    await readMessage(id);
    onSearch();
  }
  onMounted(() => {
    onSearch();
  });

  return {
    loading,
    activeName,
    form,
    dataList,
    pagination,
    onSearch,
    resetForm,
    handleSizeChange,
    handleCurrentChange,
    onDel,
    onRead,
    selectedNum,
    onSelectionCancel,
    handleSelectionChange
  };
}
